package com.cencat.controller;

import com.cencat.domain.Cat;
import com.cencat.service.CatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/cat")
public class MyController {


    // 注入serice
    @Autowired
    private CatService catService;
    /*查询全部*/
    @RequestMapping("/getAll")
    public String getAll(@ModelAttribute("msg") String msg, Model model){
        //创建列表
        List<Cat> catList = catService.getCatList();
        model.addAttribute("catList",catList);
        model.addAttribute("msg",msg);
        return "cat";
    }

    /*通过id查询*/
    @RequestMapping("/getById")
    public String getById(int id,Model model){
        Cat cat = catService.getCatById(id);
        //创建列表
        List<Cat> catList = new ArrayList<>();
        catList.add(cat);
        model.addAttribute("catList",catList);
        return "cat";
    }

    /*通过id删除*/
    @RequestMapping("/deleteById")
    public String deleteById(int id, Model model, RedirectAttributes redirectAttributes){
        catService.delete(id);
        redirectAttributes.addFlashAttribute("msg","删除成功");
        return "redirect:/cat/getAll";
    }

    /*修改id和name*/
    @RequestMapping("/updateById")
    public String updateById(Cat cat, Model model, RedirectAttributes redirectAttributes){
        catService.update(cat);
        redirectAttributes.addFlashAttribute("msg","修改成功");
        return "redirect:/cat/getAll";
    }

    /*分页查询*/
    @RequestMapping("/findByPage")
    public String findByPage(int page, int size, Model model){
        List<Cat> catList = catService.getCatByPage(page,size);
        model.addAttribute("catList",catList);
        model.addAttribute("msg","分页查询成功");
        return "cat";
    }
}
